/*
 * shred.c
 *
 *  Created on: 10 Oct 2012
 *      Author: michael
 */

#include "../../include/shredder.h"

#include <stdio.h>
#include <stdlib.h>

//Use at most 1MB per file.
#define MAX_MEMORY_USAGE 1048576

int shredder_shred_single_file(const char *filename, ShredType type) {
	if(!shredder_have_write_permissions(filename)) return -1;
	FILE *fp = fopen(filename, "r+");
	if(!fp) return -1;

	setbuf(fp, 0);

	int size = shredder_get_file_size(filename);
	int position = 0;
	unsigned char *data;
	while(position != size) {
		int amount_to_write = ((size - position) < MAX_MEMORY_USAGE ? (size - position) : MAX_MEMORY_USAGE);
		switch(type) {
		case SHREDDER_SHRED_ZEROES:
			data = shredder_create_data(amount_to_write, SHREDDER_DATA_ZEROES);
			break;

		case SHREDDER_SHRED_ONES:
			data = shredder_create_data(amount_to_write, SHREDDER_DATA_ONES);
			break;

		case SHREDDER_SHRED_RANDOM:
			data = shredder_create_data(amount_to_write, SHREDDER_DATA_RANDOM);
			break;
		}

		if(fwrite(data, 1, amount_to_write, fp) != amount_to_write) {
			fclose(fp);
			free(data);
			return -1;
		}

		position += amount_to_write;
		free(data);
	}
	fclose(fp);
	return 0;
}

